# code:utf8
import json
import logging
import math
from ispacechina.matcher import fill_img_path
from ispacechina.utils.detail_helper import DetailHelper
from zc_core.model.items import *
from zc_core.pipelines.helper.catalog_helper import CatalogHelper
from zc_core.util.encrypt_util import md5
from zc_core.util.sku_id_parser import convert_id2code

logger = logging.getLogger('rule')


# 解析catalog1列表
def parse_root_cat(response):
    root_list = json.loads(response.text).get('data', {}).get('rows', [])
    cats = list()
    for nav1 in root_list:
        cat = _build_catalog(nav1)
        cats.append(cat)

    return cats


# 解析catalog列表
def parse_sub_cat(response):
    root_list = json.loads(response.text).get('data', {}).get('rows', [])
    cats = list()
    for nav2 in root_list:
        cat2 = _build_catalog(nav2)
        cats.append(cat2)
        children = nav2.get('rows', [])
        if children:
            for nav3 in children:
                cat3 = _build_catalog(nav3)
                cats.append(cat3)

    return cats


def _build_catalog(node):
    cat = Catalog()
    cat['catalogId'] = str(node.get('guideCatalogId'))
    cat['catalogName'] = node.get('catalogName')
    pid = node.get('upperCatalogId')
    if pid == 0:
        cat['parentId'] = ''
    else:
        cat['parentId'] = str(node.get('upperCatalogId'))
    cat['level'] = node.get('catalogLevel')
    if cat['level'] == 3:
        # 1、是
        cat['leafFlag'] = 1
    else:
        # 2、否
        cat['leafFlag'] = 2
    cat['linkable'] = 1

    return cat


# 解析总页数
def parse_sku_page(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    cat_id = meta.get('catalogId')
    page_size = meta.get('pageSize')
    total_count = json.loads(response.text).get('data', {}).get('totalCount', 0)
    total_page = math.ceil(total_count / page_size)
    cat_sku_cnt = CatSkuCount()
    cat_sku_cnt['batchNo'] = batch_no
    cat_sku_cnt['catalogId'] = cat_id
    cat_sku_cnt['pageSize'] = page_size
    cat_sku_cnt['totalPage'] = total_page
    cat_sku_cnt['totalCount'] = total_count

    return cat_sku_cnt


# 解析sku列表
def parse_item(response):
    cat_helper = CatalogHelper()
    detail_helper = DetailHelper()
    meta = response.meta
    batch_no = meta.get('batchNo')
    cat3_id = meta.get('catalogId')
    cat3_name = meta.get('catalogName')

    sku_list = list()
    item_list = list()
    skus = json.loads(response.text).get('data', {}).get('result', [])
    for row in skus:
        sku_id = row.get('skuId')
        sku_name = row.get('skuName')
        sp_id = str(row.get('supplierId'))
        sp_name = row.get('supplierName')
        sp_sku_id = row.get('extSkuId')
        sale_price = row.get('salePrice')
        origin_price = row.get('marketPrice')
        if not sale_price or not origin_price or sale_price <= 0 or origin_price <= 0:
            logger.info('价格异常: sku=%s, sp_sku=%s, sp=%s' % (sku_id, sp_sku_id, sp_id))
            continue

        sku = Sku()
        sku['batchNo'] = batch_no
        sku['skuId'] = sku_id
        sku['salePrice'] = sale_price
        sku['originPrice'] = origin_price
        sku['supplierId'] = sp_id
        sku['catalog3Id'] = cat3_id
        sku['supplierSkuId'] = sp_sku_id
        sku_list.append(sku)

        item = ItemData()
        item['batchNo'] = batch_no
        item['skuId'] = sku_id
        item['skuName'] = sku_name
        item['salePrice'] = sale_price
        item['originPrice'] = origin_price
        item['supplierId'] = sp_id
        item['supplierName'] = sp_name
        if sp_sku_id:
            item['supplierSkuId'] = sp_sku_id
            plat_code = None
            if sp_id == '3' or '得力' in sp_name:
                plat_code = 'deli'
            item['supplierSkuCode'] = convert_id2code(plat_code, sp_sku_id)
        item['catalog3Id'] = cat3_id
        item['catalog3Name'] = cat3_name
        cat_helper.fill(item)
        item['skuImg'] = fill_img_path(sp_id, row.get('priPicUrl'))
        stock = row.get('skuStock', {})
        if stock and stock.get('stockStateDesc', None):
            # 均为约定默认值
            if stock.get('stockStateDesc', None) == '有货':
                item['stock'] = 999
            else:
                item['stock'] = -1
        else:
            item['stock'] = -999
        detail_helper.fill(item)
        item_list.append(item)

    return sku_list, item_list


# 解析详情页
def parse_item_detail(response):
    meta = response.meta
    sku_id = meta.get('skuId')
    batch_no = meta.get('batchNo')
    data = json.loads(response.text).get('data', {})
    if data:
        item = ItemDataSupply()
        item['batchNo'] = batch_no
        item['skuId'] = sku_id
        spu_id = data.get('upc', '')
        if spu_id and spu_id not in ['申请中', '无'] and '无' not in spu_id:
            item['spuId'] = spu_id
        if spu_id and len(spu_id) > 190:
            # spu过长特殊标记处理
            item['spuId'] = '{}_{}'.format('MD5', md5(spu_id))
        item['unit'] = data.get('saleUnit', '')
        brand = data.get('brandName', '')
        if brand:
            item['brandName'] = brand
            item['brandId'] = md5(brand)

        return item


# 解析销量
def parse_sales(response):
    meta = response.meta
    sku_id = meta.get('skuId')
    batch_no = meta.get('batchNo')
    data = json.loads(response.text).get('data', {})
    if data and 'saleNum' in data:
        item = ItemDataSupply()
        item['batchNo'] = batch_no
        item['skuId'] = sku_id
        item['soldCount'] = data.get('saleNum', 0)

        return item
